import jwt from '#Libs/auth/jwt.js';


export const jwtMiddleware = async (ctx, next) => {

    console.log(ctx);
    
    let token = ctx.header.authorization;

    if (!token) {
        return returnRes(ctx, 401, null, 'token 不能为空', false)
    }

    try {
        jwt.verify(token);
    } catch (error) {

        if (error.name == 'TokenExpiredError') {
            return returnRes(ctx, 401, null, `token 过期, msg: ${error.message}, name: ${error.name}`, false)
        } else if (error.name == 'JsonWebTokenError') {
            return returnRes(ctx, 401, null, `token 无效, msg: ${error.message}, name: ${error.name}`, false)
        } else if (error.name == 'NotBeforeError') {
            return returnRes(ctx, 401, null, `token 未生效, msg: ${error.message}, name: ${error.name}`, false)
        } else if (error.name == 'InvalidTokenError') {
            return returnRes(ctx, 401, null, `token 无效, msg: ${error.message}, name: ${error.name}`, false)
        } else {
            return returnRes(ctx, 401, null, `token 无效, msg: ${error.message}, name: ${error.name}`, false)
        }

    }

    let payload = jwt.payload(token);
    if (!payload) {
        return returnRes(ctx, 401, null, 'token 解析异常', false)
    }

    ctx.state.user = payload;

    let newToken = jwt.refresh(token);

    if (newToken) {
        ctx.set('new-token', newToken);
    }

    // 验证通过
    await next();
}

const returnRes = (ctx, code, data = null, msg, isOk) => {
    if (ctx.is('json', 'urlencoded') || ctx.is('application/json') || ctx.is('html', 'application/*')) { 
        ctx.type = 'json';
        ctx.status = code
        ctx.body = {
            code,
            msg,
            data,
            isOk
        }
        return
    }
    ctx.throw(code, msg, { data });
}